Vue Js Get Dimensions of Image: In Vue.js, you can get the size of an image by using the naturalWidth
and naturalHeight
properties of the Image
object.
To do this, you first need to create a new Image
object and set its src
attribute to the URL of the image. Then, you can access the naturalWidth
and naturalHeight
properties of the object to get the dimensions of the image in pixels.This example will teach you how to write a JavaScript program in Vue Js that can determine the size of an image.
How can I retrieve the height and width of an image using Vue.js?
This code uses the Vue.js framework to create a web application that displays the height and width of an image specified by the url
variable. The img
tag is used to display the image and the @load
event is used to trigger the getImageSize
method when the image finishes loading.
In the data
property of the Vue instance, url
, height
, and width
are defined as variables.
The getImageSize
method creates a new Image
object and sets its source to the src
attribute of the img
tag. When the image loads, the onload
function is executed, which sets the height
and width
variables to the corresponding properties of the img
object.
Finally, the Vue instance is mounted to the #app
element of the HTML document. When the application loads, the image is displayed and the getImageSize
method is executed to retrieve and display the image dimensions.
Vue Js Get Image Height And Width Example
<div id="app">
<p>Height of Image:{{height}}px</p>
<p>Width of Image:{{width}}px</p>
<img ref="image" :src="url" @load="getImageSize">
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
url: 'https://www.sarkarinaukriexams.com/images/post/1670773657Capture--42343254324.PNG',
height: '',
width: '',
};
},
methods: {
getImageSize() {
const img = new Image();
img.src = this.$refs.image.src;
img.onload = () => {
this.width = img.width;
this.height = img.height;
};
}
},
});
</script>